package JDBC;

import Utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * JDBC中操作事务
 * 操作：
 *  1. 开启事务
 *  2. 提交事务
 *  3. 回滚事务
 *
 * 案例：张三给李四转账500元
 * 数据库：bank
 * 表：user
 *
 * @author Mc.Chai
 * @program: JavaWeb
 * @create 2021-12-15-17:55 17:55
 */
public class JDBCAffairs {
    public static void main(String[] args) {
        Connection connection=null;
        PreparedStatement preparedStatement1=null;
        PreparedStatement preparedStatement2=null;
        try {
            connection = JDBCUtils.getConnection();
            //开启事务！
            connection.setAutoCommit(false);
            String sql1="update user set salary=salary-? where id=?";
            String sql2="update user set salary=salary+? where id=?";
            preparedStatement1 = connection.prepareStatement(sql1);
            preparedStatement2 = connection.prepareStatement(sql2);
            preparedStatement1.setInt(1,500);
            preparedStatement1.setInt(2,1);
            preparedStatement2.setInt(1,500);
            preparedStatement2.setInt(2,2);
            preparedStatement1.executeUpdate();
            //System.out.println(1/0);//产生异常，需要事务的回滚
            preparedStatement2.executeUpdate();
            //执行事务
            connection.commit();
        } catch (SQLException throwables) {
            //进行事务的回滚
            if (connection!=null){
                try {
                    connection.rollback();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            throwables.printStackTrace();
        }finally {
            JDBCUtils.close(preparedStatement1,connection);
            JDBCUtils.close(preparedStatement2,null);
        }
    }
}
